package cc.ok200.muzhi;

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;

public class MarketPluginAdapter extends RecyclerView.Adapter<MarketPluginAdapter.MarketPluginViewHolder> {

    private static final String TAG = "MarketPluginAdapter";
    private Context context;
    private JSONArray plugins;
    private OnItemClickListener onItemClickListener;
    private OnDownloadClickListener onDownloadClickListener;

    public MarketPluginAdapter(Context context, JSONArray plugins) {
        this.context = context;
        this.plugins = plugins;
    }

    @NonNull
    @Override
    public MarketPluginViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_market_plugin, parent, false);
        return new MarketPluginViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MarketPluginViewHolder holder, int position) {
        try {
            JSONObject plugin = plugins.getJSONObject(position);
            
            holder.tvPluginType.setText(plugin.getString("type"));
            holder.tvPluginName.setText(plugin.getString("name"));
            holder.tvPluginDescription.setText(plugin.getString("description"));
            holder.tvPluginAuthor.setText(plugin.getString("author"));
            holder.tvPrice.setText(plugin.getString("price"));
            
            // 格式化下载次数
            int downloadCount = plugin.getInt("download_count");
            holder.tvDownloadCount.setText(formatDownloadCount(downloadCount) + " 下载");
            
            // 使用GlideApp加载图片
            try {
                RequestOptions options = new RequestOptions()
                    .placeholder(R.mipmap.ic_launcher)
                    .error(R.mipmap.ic_launcher)
                    .diskCacheStrategy(DiskCacheStrategy.ALL);
                    
                GlideApp.with(context)
                    .load(plugin.getString("avatar"))
                    .apply(options)
                    .into(holder.ivPluginIcon);
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(context, "图片加载失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
            
            // 设置点击事件
            holder.itemView.setOnClickListener(v -> {
                if (onItemClickListener != null) {
                    onItemClickListener.onItemClick(position, plugin);
                }
            });
            
            // 设置下载按钮点击事件
            holder.btnDownload.setOnClickListener(v -> {
                if (onDownloadClickListener != null) {
                    onDownloadClickListener.onDownloadClick(position, plugin);
                }
            });
            
        } catch (JSONException e) {
            Log.e(TAG, "JSON解析错误: " + e.getMessage());
        }
    }

    private String formatDownloadCount(int count) {
        if (count < 1000) {
            return String.valueOf(count);
        } else if (count < 10000) {
            float k = count / 1000f;
            DecimalFormat df = new DecimalFormat("#.#");
            return df.format(k) + "K";
        } else if (count < 1000000) {
            float k = count / 1000f;
            DecimalFormat df = new DecimalFormat("#");
            return df.format(k) + "K";
        } else {
            float m = count / 1000000f;
            DecimalFormat df = new DecimalFormat("#.#");
            return df.format(m) + "M";
        }
    }

    @Override
    public int getItemCount() {
        return plugins != null ? plugins.length() : 0;
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }
    
    public void setOnDownloadClickListener(OnDownloadClickListener onDownloadClickListener) {
        this.onDownloadClickListener = onDownloadClickListener;
    }

    public interface OnItemClickListener {
        void onItemClick(int position, JSONObject plugin);
    }
    
    public interface OnDownloadClickListener {
        void onDownloadClick(int position, JSONObject plugin);
    }

    static class MarketPluginViewHolder extends RecyclerView.ViewHolder {
        ImageView ivPluginIcon;
        TextView tvPluginType;
        TextView tvPluginName;
        TextView tvPluginDescription;
        TextView tvPluginAuthor;
        TextView tvDownloadCount;
        TextView tvPrice;
        Button btnDownload;

        public MarketPluginViewHolder(@NonNull View itemView) {
            super(itemView);
            ivPluginIcon = itemView.findViewById(R.id.iv_plugin_icon);
            tvPluginType = itemView.findViewById(R.id.tv_plugin_type);
            tvPluginName = itemView.findViewById(R.id.tv_plugin_name);
            tvPluginDescription = itemView.findViewById(R.id.tv_plugin_description);
            tvPluginAuthor = itemView.findViewById(R.id.tv_plugin_author);
            tvDownloadCount = itemView.findViewById(R.id.tv_download_count);
            tvPrice = itemView.findViewById(R.id.tv_price);
            btnDownload = itemView.findViewById(R.id.btn_download);
        }
    }
} 